<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          <span class="titleTime">
            {{
              paginationReactive.month?.split('-')[0] +
              '年' +
              paginationReactive.month?.split('-')[1] +
              '月'
            }}
          </span>
          姓名:
          <NInput style="width: 200rem" placeholder="请输入姓名" v-model:value="paginationReactive.userName" clearable />
          考勤时间:
          <NDatePicker input-readonly style="width: 200rem" placeholder="请输入标题"
            v-model:formatted-value="paginationReactive.month" type="month" />
          部门:
          <NSelect :options="depList" placeholder="请选择部门" clearable style="width: 250rem"
            v-model:value="paginationReactive.deptId" label-field="name" value-field="value" filterable
             />
          <NButton type="primary" style="width: 78rem" ghost
            @click="() => ((paginationReactive.page = 1), getWorkList())">
            查询
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" scroll-x="4800" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
    <VDialogContent @close="contentVisible = false" @submit="submit" title="删除提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗？
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { h, reactive, onDeactivated, ref, watch } from 'vue'
import {
  NSpace,
  NInput,
  NButton,
  NDataTable,
  NPagination,
  NSelect,
  useMessage,
  NModal,
  NDatePicker
} from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import router from '@/router'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { CheckModel } from '@/api/checkRules'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute } from 'vue-router'
import { useViewerStore } from '../Common/store'

const message = useMessage()
const useStore = useViewerStore()
const route = useRoute()
let columns: DataTableColumns = []
// 上一页下一页
const paginationReactive: any = reactive<Record<string, any>>({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 50,
  userName: null, //用户名称
  month: null, //月份
  deptId: null, //部门
  onChange: (page: number) => {
    paginationReactive.page = page
    getWorkList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getWorkList()
  }
})
// 删除
const workId = ref()
const contentVisible = ref(false)
const submit = async () => {
  tableLoading.value = true
  contentVisible.value = false
  const [error, res] = await sendRequest<HttpResponse<CheckModel>>({
    module: 'checkRules',
    api: 'workDelete',
    override: {
      data: {
        month: paginationReactive.month,
        userId: workId.value
      }
    }
  })
  if (error) return message.error('删除失败'), (tableLoading.value = false)
  if (res.code !== 0) return message.error('删除失败'), (tableLoading.value = false)
  message.success('删除成功')
  getWorkList()
}
// 获取列表
const tableData: any = ref([])
const tableLoading = ref(false)
const getWorkList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<CheckModel>>({
    module: 'checkRules',
    api: 'workList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        userName: paginationReactive.userName,
        month: paginationReactive.month,
        deptId: paginationReactive.deptId
      }
    }
  })
  if (error) return message.error(error.message), (tableLoading.value = false)
  if (res.code !== 0) return message.error(res.msg), (tableLoading.value = false)
  await handleTableData(res.data.list)
  paginationReactive.itemCount = res.data.totalCount
  tableLoading.value = false
}
// 处理tableDate数据
const handleTableData = (data: any) => {
  if (!data.length) return (tableData.value = [])
  tableData.value = []

  const tmp: any = []
  data.map((it: any, index: any) => {
    const list: any = {}
    it.map((c: any, ind: any) => {
      if (ind == 0) return
      if (index == 0) {
        if (c == '姓名')
          return tmp.push({ title: c, key: c, width: 100, align: 'center', fixed: 'left' })
        return tmp.push({ title: c, key: c, width: 100, align: 'center' })
      }
      list[tmp[ind - 1]['key']] = c
      list['id'] = data[index][0]
    })
    if (index != 0) return (tableData.value = [...tableData.value, list])
  })
  tmp.push({
    title: '操作',
    key: 'action',
    align: 'center',
    width: 140,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            router.push({
              path: '/OA/Office/WorkUpdate',
              query: { id: row.id, month: paginationReactive.month }
            })
          }
        },
        {
          default: () => '编辑'
        }
      ),
      // h(
      //   NButton,
      //   {
      //     type: 'primary',
      //     quaternary: true,
      //     color: useStore.color['delete'],
      //     onClick: () => {
      //       workId.value = row.id
      //       contentVisible.value = true
      //     }
      //   },
      //   {
      //     default: () => '删除'
      //   }
      // )
    ]
  })
  columns = tmp
}
// 获取部门
const depList: any = ref([])
const getDepList = async () => {
  const [error, res] = await sendRequest<HttpResponse<CheckModel>>({
    module: 'overTime',
    api: 'BbgDeptList'
  })
  if (error) return
  if (res.code !== 0) return
  depList.value = res.data
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,getWorkList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  () => {
    if (route.path == '/OA/Office/checkWork') {
      getDepList()
      const date = new Date().toLocaleDateString().split('/')
      paginationReactive.month = date[0] + '-' + (Number(date[1]) < 10 ? '0' + date[1] : date[1])
      getWorkList()
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}

.titleTime {
  font-size: 24rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  color: #5fb17f;
}
</style>
